<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgpu - caustics</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="example.css">
	</head>
	<body>

		<div id="info">
			<a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>

			<div class="title-wrapper">
				<a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Caustics</span>
			</div>

			<small>Realtime caustics effect.</small>
		</div>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.webgpu.js",
					"three/webgpu": "../build/three.webgpu.js",
					"three/tsl": "../build/three.tsl.js",
					"three/addons/": "./jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three/webgpu';

			import { uniform, refract, div, positionViewDirection, positionLocal, normalView, texture, Fn, vec2, vec3, vec4 } from 'three/tsl';

			import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
			import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
			import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';

			import { Inspector } from 'three/addons/inspector/Inspector.js';

			let camera, scene, renderer, controls;
			let gltf;

			init();

			async function init() {

				camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 0.025, 5 );
				camera.position.set( - 0.5, 0.35, 0.2 );

				scene = new THREE.Scene();

				// light

				const spotLight = new THREE.SpotLight( 0xffffff, 1 );
				spotLight.position.set( .2, .3, .2 );
				spotLight.castShadow = true;
				spotLight.angle = Math.PI / 6;
				spotLight.penumbra = 1;
				spotLight.decay = 2;
				spotLight.distance = 0;
				spotLight.shadow.mapType = THREE.HalfFloatType; // For HDR Caustics
				spotLight.shadow.mapSize.width = 1024;
				spotLight.shadow.mapSize.height = 1024;
				spotLight.shadow.camera.near = .1;
				spotLight.shadow.camera.far = 1;
				spotLight.shadow.bias = - .003;
				spotLight.shadow.intensity = .95;
				scene.add( spotLight );

				// model / textures

				const dracoLoader = new DRACOLoader();
				dracoLoader.setDecoderPath( 'jsm/libs/draco/' );
				dracoLoader.setDecoderConfig( { type: 'js' } );

				gltf = ( await new GLTFLoader().setDRACOLoader( dracoLoader ).loadAsync( './models/gltf/duck.glb' ) ).scene;
				gltf.scale.setScalar( .5 );
				scene.add( gltf );

				const causticMap = new THREE.TextureLoader().load( './textures/opengameart/Caustic_Free.jpg' );
				causticMap.wrapS = causticMap.wrapT = THREE.RepeatWrapping;
				causticMap.colorSpace = THREE.SRGBColorSpace;

				// objects / material

				const duck = gltf.children[ 0 ];
				duck.material = new THREE.MeshPhysicalNodeMaterial();
				duck.material.side = THREE.DoubleSide;
				duck.material.transparent = true;
				duck.material.color = new THREE.Color( 0xFFD700 );
				duck.material.transmission = 1;
				duck.material.thickness = .25;
				duck.material.ior = 1.5;
				duck.material.metalness = 0;
				duck.material.roughness = .1;
				duck.castShadow = true;

				// tsl shader

				const causticOcclusion = uniform( 20 );

				duck.material.castShadowPositionNode = Fn( () => {

					// optional: add some distortion to the geometry shadow position if needed

					return positionLocal;

				} )();

				duck.material.castShadowNode = Fn( () => {

					const refractionVector = refract( positionViewDirection.negate(), normalView, div( 1.0, duck.material.ior ) ).normalize();
					const viewZ = normalView.z.pow( causticOcclusion );

					const textureUV = refractionVector.xy.mul( .6 );

					const causticColor = uniform( duck.material.color );
					const chromaticAberrationOffset = normalView.z.pow( - .9 ).mul( .004 );

					const causticProjection = vec3(
						texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset.negate(), 0 ) ) ).r,
						texture( causticMap, textureUV.add( vec2( 0, chromaticAberrationOffset.negate() ) ) ).g,
						texture( causticMap, textureUV.add( vec2( chromaticAberrationOffset, chromaticAberrationOffset ) ) ).b
					);

					return causticProjection.mul( viewZ.mul( 25 ) ).add( viewZ ).mul( causticColor );

				} )();

				//

				const textureLoader = new THREE.TextureLoader();

				// glass

				const colorMap = textureLoader.load( 'textures/colors.png' );
				colorMap.wrapS = colorMap.wrapT = THREE.RepeatWrapping;
				colorMap.colorSpace = THREE.SRGBColorSpace;

				const glassMaterial = new THREE.MeshPhysicalNodeMaterial();
				glassMaterial.map = colorMap;
				glassMaterial.side = THREE.DoubleSide;
				glassMaterial.transparent = true;
				glassMaterial.color = new THREE.Color( 0xffffff );
				glassMaterial.transmission = 1;
				glassMaterial.ior = 1.5;
				glassMaterial.metalness = 0;
				glassMaterial.roughness = .1;
				glassMaterial.castShadowNode = vec4( texture( colorMap ).rgb, .8 );

				const glass = new THREE.Mesh( new THREE.PlaneGeometry( .2, .2 ), glassMaterial );
				glass.position.y = .1;
				glass.castShadow = true;
				glass.visible = false;
				scene.add( glass );

				// ground

				const map = textureLoader.load( 'textures/hardwood2_diffuse.jpg' );
				map.wrapS = map.wrapT = THREE.RepeatWrapping;
				map.repeat.set( 10, 10 );

				const geometry = new THREE.PlaneGeometry( 2, 2 );
				const material = new THREE.MeshStandardMaterial( { color: 0x999999, map } );

				const ground = new THREE.Mesh( geometry, material );
				ground.rotation.x = - Math.PI / 2;
				ground.receiveShadow = true;
				scene.add( ground );

				// renderer

				renderer = new THREE.WebGPURenderer( { antialias: true } );
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				renderer.setAnimationLoop( animate );
				renderer.shadowMap.enabled = true;
				renderer.inspector = new Inspector();
				document.body.appendChild( renderer.domElement );

				// gui

				const gui = renderer.inspector.createParameters( 'Settings' );
				gui.add( causticOcclusion, 'value', 0, 20 ).name( 'caustic occlusion' );
				gui.addColor( duck.material, 'color' ).name( 'material color' );
				gui.add( { model: 'duck' }, 'model', [
					'duck',
					'glass'
				] ).onChange( model => {

					duck.visible = glass.visible = false;

					if ( model === 'duck' ) {

						duck.visible = true;

					} else if ( model === 'glass' ) {

						glass.visible = true;

					}

				} );


				// controls

				controls = new OrbitControls( camera, renderer.domElement );
				controls.maxDistance = 3;
				controls.maxPolarAngle = Math.PI / 2;

				window.addEventListener( 'resize', onWindowResize );

			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

			}

			function animate() {

				for ( const mesh of gltf.children ) {

					mesh.rotation.y -= .01;

				}

				controls.update();

				renderer.render( scene, camera );

			}

		</script>
	</body>
</html>
